package com.sun.showcase.conf.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.sun.showcase.biz.basic.service.UserInfoService;
import com.sun.showcase.client.domain.basic.UserInfo;
import com.sun.showcase.client.query.basic.UserInfoQuery;

/**
 * 存储用户登录信息
 *
 */
public class LoginSuccesshandler extends SavedRequestAwareAuthenticationSuccessHandler{

	@Autowired
	private UserInfoService userInfoService;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)throws ServletException, IOException {
		
		UserInfo t = (UserInfo) authentication.getPrincipal();
		
		//存储用户登录信息
		if(null != t){
			
			UserInfoQuery query = new UserInfoQuery();
			
			//query.setLastLoginIp(IPUtil.getIpAddress(request));
			query.setLastLoginTime(new Date());
			
			query.setId(t.getId());
			userInfoService.modify(query);
		}
		
		HttpSession session = request.getSession(false);
		
		//清除缓存的请求地址
		if(session != null){
			
			session.removeAttribute("SPRING_SECURITY_SAVED_REQUEST");
		}
		
		super.onAuthenticationSuccess(request, response, authentication);
	}
	  
}
